import java.util.Arrays;

/**
 * @ClassName LC16
 * @Author ykx
 * @Date 2024/3/4 12:15
 * @Version 1.0
 */
public class LC16 {
    public static void main(String[] args) {

    }

    public int threeSumClosest(int[] nums, int target) {
        // 返回结果
        int result = nums[0] + nums[1] + nums[2];

        // 先对数组排序
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            // 分别定义左右指针
            int left = i + 1;
            int right = nums.length - 1;

            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (Math.abs(sum - target) < Math.abs(result - target)) {
                    result = sum;
                }
                if (sum > target) {
                    right--;
                } else if (sum < target) {
                    left++;
                } else {
                    return sum;
                }

            }

        }

        return result;
    }
}
